<?php

// amespace Library\StringCodeClass;
class StringCode {

    public static function GetCsubStr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
        $charset = empty($charset) ? 'utf-8' : $charset;
        $search = array(
            '((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9\-\.\[\]_\"\'\$\x7f-\xff]+\])*)',
            '/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU', // 去掉 javascript
            '/(<[^>]*)on[a-zA-Z] \s*=([^>]*>)/isU',
            '/<[\/\!]*?[^<>]*?>/si', // 去掉 HTML 标记
            '/([\r\n])[\s]+/i', // 去掉空白字符
            '/&(quot|#34);/i', // 替换 HTML 实体
            '/&(amp|#38);/i',
            '/&(lt|#60);/i',
            '/&(gt|#62);/i',
            '/&(nbsp|#160);/i',
            '/&(iexcl|#161);/i',
            '/&(cent|#162);/i',
            '/&(pound|#163);/i',
            '/&(copy|#169);/i',
            '/&#(\d+);/e',
            '/<\?/si',
            '/\?>/si'
        );
        $replace = array(
            '([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)',
            '&lt;\\1\\2\\3&gt;',
            '\\1\\2',
            "",
            "\r\n",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            '&lt;?',
            '?&gt;'
        );
        $str = preg_replace($search, $replace, $str);
        if (function_exists("mb_substr")) {
            if (mb_strlen($str, $charset) <= $length) {
                return $str;
            }
            $slice = mb_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            if (!empty($match[0]) && count($match[0]) <= $length) {
                return $str;
            }
            $slice = join("", array_slice($match[0], $start, $length));
        }
        if ($suffix) {
            return $slice . "…";
        }
        return $slice;
    }

    public static function Fescape($string, $esc_type = 'html', $char_set = 'ISO-8859-1') {
        switch ($esc_type) {
            case 'html':
                return htmlspecialchars($string, ENT_QUOTES, $char_set);
            case 'htmlall':
                return htmlentities($string, ENT_QUOTES, $char_set);
            case 'url':
                return rawurlencode($string);
            case 'urlpathinfo':
                return str_replace('%2F', '/', rawurlencode($string));
            case 'quotes':
                // escape unescaped single quotes
                return preg_replace("%(?<!\\\\)'%", "\\'", $string);
            case 'hex':
                // escape every character into hex
                $return = '';
                for ($x = 0; $x < strlen($string); $x++) {
                    $return.='%' . bin2hex($string[$x]);
                }
                return $return;
            case 'hexentity':
                $return = '';
                for ($x = 0; $x < strlen($string); $x++) {
                    $return.='&#x' . bin2hex($string[$x]) . ';';
                }
                return $return;
            case 'decentity':
                $return = '';
                for ($x = 0; $x < strlen($string); $x++) {
                    $return.='&#' . ord($string[$x]) . ';';
                }
                return $return;
            case 'javascript':
                // escape quotes and backslashes, newlines, etc.
                return strtr($string, array(
                    '\\' => '\\\\',
                    "'" => "\\'",
                    '"' => '\\"',
                    "\r" => '\\r',
                    "\n" => '\\n',
                    '</' => '<\/'
                ));
            case 'mail':
                // safe way to display e-mail address on a web page
                return str_replace(array(
                    '@',
                    '.'
                        ), array(
                    '[AT] ',
                    '[DOT] '
                        ), $string);
            case 'nonstd':
                // escape non-standard chars, such as ms document quotes
                $_res = '';
                for ($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {
                    $_ord = ord(substr($string, $_i, 1));
                    // non-standard char, escape it
                    if ($_ord >= 126) {
                        $_res.='&#' . $_ord . ';';
                    } else {
                        $_res.=substr($string, $_i, 1);
                    }
                }
                return $_res;
            default:
                return $string;
        }
    }

    public static function HightLight($str, $keywords) {
        if (!is_array($keywords)) {
            $keywords = explode(" ", $keywords);
        }
        foreach ($keywords as $key => $value) {
            if (!empty($value)) {
                $p = array(
                    '/\./si',
                    '/\//si',
                    '/\{/si',
                    '/\}/si',
                    '/\?/si',
                    '/\[/si',
                    '/\]/si',
                    '/\|/si',
                    '/\(/si',
                    '/\)/si'
                );
                $r = array(
                    '\.',
                    '\/',
                    '\{',
                    '\}',
                    '\?',
                    '\[',
                    '\]',
                    '\|',
                    '\(',
                    '\)'
                );
                $pattern[] = preg_replace($p, $r, addslashes($value));
            }
        }
        if (is_array($pattern)) {
            $str = preg_replace("/(" . implode("|", $pattern) . ")/si", "<font color=red>\\1</font>", $str);
        }
        return $str;
    }

    public static function RandomCode($leng = 12, $type = "all") {
        $leng = $leng > 0 ? intval($leng) : 12;
        $str = "";
        if ($type == 'num') {
            for ($i = 0; $i < $leng; $i++) {
                mt_srand(doubleval(microtime() * 1000000));
                $str.=chr(mt_rand(48, 57));
            }
        } elseif ($type == 'capital') {
            for ($i = 0; $i < $leng; $i++) {
                mt_srand(doubleval(microtime() * 1000000));
                $str.=chr(mt_rand(65, 90));
            }
        } elseif ($type == 'lower') {
            for ($i = 0; $i < $leng; $i++) {
                mt_srand(doubleval(microtime() * 1000000));
                $str.=chr(mt_rand(97, 122));
            }
        } elseif ($type == 'time') {
            $str = date('YmdHis');
            $str.=self::RandomCode($leng, 'num');
        } else {
            $char = array(
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "0",
                "a",
                "b",
                "c",
                "d",
                "e",
                "f",
                "g",
                "h",
                "i",
                "j",
                "k",
                "l",
                "m",
                "n",
                "o",
                "p",
                "q",
                "r",
                "s",
                "t",
                "u",
                "v",
                "w",
                "x",
                "y",
                "z",
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "K",
                "L",
                "M",
                "N",
                "O",
                "P",
                "Q",
                "R",
                "S",
                "T",
                "U",
                "V",
                "W",
                "X",
                "Y",
                "Z"
            );
            shuffle($char);
            $n = count($char) - 1;
            $str = "";
            for ($i = 0; $i < $leng; $i++) {
                mt_srand(doubleval(microtime() * 1000000));
                $m = mt_rand(0, $n);
                $str.=$char[$m];
            }
        }
        return $str;
    }

    /**
     * semiangle 全角转换为半角
     *
     * @param string $str
     * @return string 返回全角转换为半角后的字符串
     */
    public static function Semiangle($str) {
        $arr = array(
            '０' => '0',
            '１' => '1',
            '２' => '2',
            '３' => '3',
            '４' => '4',
            '５' => '5',
            '６' => '6',
            '７' => '7',
            '８' => '8',
            '９' => '9',
            '（' => '(',
            '）' => ')',
            '［' => '[',
            '］' => ']',
            '【' => '[',
            '】' => ']',
            '〖' => '[',
            '〗' => ']',
            '「' => '[',
            '」' => ']',
            '『' => '[',
            '』' => ']',
            '｛' => '{',
            '｝' => '}',
            '《' => '<',
            '》' => '>',
            '％' => '%',
            '＋' => '+',
            '—' => '-',
            '－' => '-',
            '～' => '-',
            '：' => ':',
            '。' => '.',
            '、' => ',',
            '，' => '.',
            '、' => '.',
            '；' => ',',
            '？' => '?',
            '！' => '!',
            '…' => '-',
            '‖' => '|',
            '＂' => '"',
            '＇' => '\'',
            '｀' => '\'',
            '｜' => '|',
            '〃' => '"',
            '　' => ' '
        );
        return strtr($str, $arr);
    }

    /**
     * Gb2Utf8 转换gbk字符到utf8
     *
     * @param string $gbstr
     * @return string 转换后的字符串
     */
    public static function Gb2Utf8($gbstr) {
        $ishigh = preg_match('/[\x80-\xff]/', $gbstr);
        if (!$ishigh)
            return $gbstr;
        $isutf8 = preg_match('/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $gbstr);
        if ($isutf8)
            return $gbstr;
        if (preg_match("/^([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}/", $gbstr) == true || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}$/", $gbstr) == true || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){2,}/", $gbstr) == true)
            return $gbstr;
        if (function_exists('mb_convert_encoding'))
            return mb_convert_encoding($gbstr, 'utf-8', 'GBK');
        else if (function_exists('iconv'))
            return iconv("GBK", "utf-8", $gbstr);
        return $gbstr;
    }

    /**
     * Utf82Gb 转换utf8字符到gbk
     *
     * @param string $gbstr
     * @return string 转换后的字符串
     */
    public static function Utf82Gbk($utfstr) {
        if (function_exists('mb_convert_encoding'))
            return mb_convert_encoding($utfstr, 'GBK', 'utf-8');
        else if (function_exists('iconv'))
            return iconv("utf-8", "GBK", $utfstr);
        return $utfstr;
    }

    public static function IsEmail($value) {
        if (!is_string($value)) {
            return false;
        }
        $matches = array();
        $length = true;
        if ((strpos($value, '..') !== false) || (!preg_match('/^(.+)@([\w\.]+)$/i', $value, $matches))) {
            return false;
        }
        $_localPart = $matches[1];
        // $_hostname = $matches[2].$matches[3];
        // if ((strlen($_localPart) > 64) || (strlen($_hostname) > 255)) {
        if ((strlen($_localPart) > 64)) {
            $length = false;
        }
        $local = false;
        // Dot-atom characters are: 1*atext *("." 1*atext)
        // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
        // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
        $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e';
        if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $_localPart)) {
            $local = true;
        } else {
            $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
            $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
            $ws = '\x20\x09';
            if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $_localPart)) {
                $local = true;
            }
        }
        // If both parts valid, return true
        if ($local && $length) {
            return true;
        }
        return false;
    }

    public static function GetSize($number) {
        if ($number < 100) {
            return round($number, 4) . 'b';
        }
        $number = $number / 1024;
        if ($number < 100) {
            return round($number, 2) . 'k';
        }
        $number = $number / 1024;
        if ($number < 100) {
            return round($number, 2) . 'm';
        }
        $number = $number / 1024;
        if ($number < 100) {
            return round($number, 2) . 'g';
        }
    }

    //计算折扣率
    public static function Discount($s_price, $n_price) {
        return round(10 / ($s_price / $n_price), 1);
    }

    public static function doUrlimage($data) {
        if (!empty($data)){
            if(is_array($data)){
                foreach ($data as $k => $v) {
                    $v = str_replace('http://crm.app.qiche100.com', '', $v);
                    if(strpos($v,'http://') === false){
                        $data[$k] = BASE_ATTACH . $v;
                    }else{
                        $data[$k] = $v;
                    }
                }
            }else{
                $data = BASE_ATTACH . $data;
            }
        }
        return $data;
    }

    /**
     * 计算年龄
     * @param type $cardno
     */
    public static function getAge($birthday) {
        $age = strtotime($birthday);
        if ($age === false) {
            return false;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        $now = strtotime("now");
        list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
        $age = $y2 - $y1;
        if ((int) ($m2 . $d2) < (int) ($m1 . $d1))
            $age -= 1;
        return $age;
    }
    public function ceil_format($num){
        return ceil($num*100)/100;
    }
    
}